import { Component } from "inferno";
import * as matrixcs from "matrix-js-sdk";
import ChatDMItem from "./ChatDMItem";
import TextListItem from "./ui/TextListItem";
import ListView from "./ListView";
import { startDM } from "./utils";
import personIcon from "./person_icon.png";

const AVATAR_WIDTH = 36;
const AVATAR_HEIGHT = 36;

class DMsView extends Component {
  handleKeyDown = (evt) => {
    if (evt.key === "Call" || evt.key === "c") {
      if (window.confirm("You sure wanna call?"))
        this.placeCall(this.currentRoomId);
    }
  };

  cursorChangeCb = (cursor) => {
    this.currentRoomId = this.rooms[cursor].roomId;
  };

  getDMs = (room) =>
    room.getJoinedMemberCount() === 2 && room.getMyMembership() === "join";

  constructor(props) {
    super(props);
    this.updateFocusRoomCb = props.updateFocusRoomCb;
    this.softKeyRef = props.softKeyRef;
    this.currentRoomId = null;
    this.rooms = [];
    this.openRoom = props.openRoom;
    this.placeCall = props.placeCall;
  }

  componentDidMount() {
    document.addEventListener("keydown", this.handleKeyDown);
  }

  componentWillUnmount() {
    document.removeEventListener("keydown", this.handleKeyDown);
  }

  render() {
    const soft = this.softKeyRef.current;
    soft.setState({ centerText: "Open", leftText: "Quit", rightText: "+" });
    soft.centerCb = () => this.openRoom(this.currentRoomId);
    soft.leftCb = window.close;
    soft.rightCb = () => {
      let uid;
      if ((uid = prompt("User address"))) {
        const room = window.mClient
          .getVisibleRooms()
          .filter(this.getDMs)
          .filter((room) => room.guessDMUserId() === uid);
        if (room.length === 0) {
          startDM(window.mClient, uid);
        } else {
          this.openRoom(room[0].roomId);
        }
      }
    };

    this.rooms = window.mClient.getVisibleRooms().filter(this.getDMs);
    let renderedRooms = this.rooms.map((room) => {
      const theOther = room.guessDMUserId();
      const mxcUrl = window.mClient.getUser(theOther).avatarUrl;
      let avatarUrl;
      if (mxcUrl) {
        avatarUrl = matrixcs.getHttpUriForMxc(
          window.mClient.getHomeserverUrl(),
          mxcUrl,
          AVATAR_WIDTH,
          AVATAR_HEIGHT,
          "scale",
          true
        );
      } else {
        avatarUrl = personIcon;
      }
      return <ChatDMItem room={room} avatar={avatarUrl} />;
    });
    if (renderedRooms.length === 0) {
      renderedRooms.push(<TextListItem primary="No DM :(" />);
    }
    return (
      <ListView
        cursor={0}
        cursorChangeCb={this.cursorChangeCb}
        $HasNonKeyedChildren
      >
        {renderedRooms}
      </ListView>
    );
  }
}

export default DMsView;
